package com.ding.easycontroller.controller;

import com.ding.easycontroller.work.Controller;
import com.ding.easycontroller.work.Service;
import com.ding.easycontroller.work.Script;
import com.ding.easycontroller.model.R;
import com.ding.easycontroller.service.ControllerService;
import com.ding.easycontroller.service.ServiceService;
import com.ding.easycontroller.utils.FileUtils;
import com.ding.easycontroller.utils.ScriptUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 提供 一键导出所有脚本
 * 选择性导出部分脚本
 */

@RestController
@RequestMapping("/_script")
public class _Script {

/*

    @Autowired
    private ControllerService controllerService;

    @Autowired
    private ServiceService moduleService;

    //查看全部脚本

    @GetMapping("/all")
    public List<Script> listAll() {
        List<Controller> controllers = controllerService.listAll();
        List<Service> modules = moduleService.listAll();
        List<Script> all = new ArrayList<>();
        all.addAll(controllers);
        all.addAll(modules);
        List<Script> r = new ArrayList<>();
        for (Script script : all) {
            Script s = new Script();
            BeanUtils.copyProperties(script, s);
            r.tryAdd(s);
        }
        return r;
    }

    //一键导出全部(导出统一以zip导出)

    @GetMapping("/exportAll")
    public void exportAll(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=all.ec" );
        ServletOutputStream outputStream = response.getOutputStream();
        List<File> all=ScriptUtils.listAll();
        FileUtils.filesToZipOutputStream(all,outputStream);
    }


    //一键导入全部
    @PostMapping("/importAll")
    public R importAll(HttpServletRequest  request) throws IOException {

        //创建一个临时目录
        File tempFile = File.createTempFile("ec_", "");
        tempFile.delete();
        ServletInputStream inputStream = request.getInputStream();
        FileUtils.zipInputStreamToFiles(inputStream,tempFile);

        //从临时文件夹加载脚本文件
        ScriptUtils.loadScript(tempFile);

        return R.OK;

    }

    //选择部分id导出


    //预导入,解压压缩文件,呈现类型和描述和js

    //选择部分导入
*/

}
